using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using System.Xml;

 
public partial class _Default : System.Web.UI.Page
{
	DBControl conDB = new DBControl(WebConfigurationManager.ConnectionStrings["TestBase"].ConnectionString);

	protected void Page_Load(object sender, EventArgs e)
    {
        FillCatTable();
    }

	protected void FillCatTable()
    {
		int rowNumber = 0;
		int cellNumber = 0;
        int ff = 1;

		List<TableCell> cells = new List<TableCell>();
		List<CategoryDetails> list = conDB.GetCategoryList();

		for (int i = 1; i < list.Count; i++)
		{
			if (list[i].ParentId == 0)
			{
				if ((i - 1) % 3 == 0)
					rowNumber = CatTable.Rows.Add(CreateTableRow(VerticalAlign.Top));
				TableCell cell = CreateTableCell(33, list[i].CategoryId);
				CatTable.Rows[rowNumber].Cells.Add(cell);
				cells.Add(cell);
				FillCatTableCell(list[i], cell, true);
			}
			else
			{
				while (cells[cellNumber].ID != list[i].ParentId.ToString())
					cellNumber++;

				if (cellNumber < cells.Count && list[i].ShowInShortList)
					FillCatTableCell(list[i], cells[cellNumber], false);
			}
		}

		foreach (TableCell cell in cells)
			if (cell.Controls.Count > 1)
				cell.Controls.RemoveAt(cell.Controls.Count - 1);
    }

	protected void FillCatTableCell(CategoryDetails catDetails, TableCell cell, bool first)
	{
		if (first)
		{
			cell.Controls.Add(CreateHyperLink(catDetails.CategoryName, "~/Category.aspx?id=" + catDetails.CategoryId, 12, true));
			cell.Controls.Add(CreateLiteral("<br/>"));
		}
		else
		{
			cell.Controls.Add(CreateHyperLink(catDetails.CategoryName, "~/Category.aspx?id=" + catDetails.CategoryId, 10, false));
			cell.Controls.Add(CreateLiteral(", "));
		}
	}

	private TableRow CreateTableRow(VerticalAlign verticalAlign)
	{
		TableRow row = new TableRow();
		row.VerticalAlign = verticalAlign;
		return row;
	}

	private TableCell CreateTableCell(double percentage, long id)
	{
		TableCell cell = new TableCell();
		cell.ID = id.ToString();
		cell.Width = Unit.Percentage(percentage);
		return cell;
	}

	private HyperLink CreateHyperLink(string text, string navigateUrl, int fontsize, bool bold)
	{
		HyperLink hyperLink = new HyperLink();
		hyperLink.Text = text;
		hyperLink.NavigateUrl = navigateUrl;
		hyperLink.Font.Name = "Arial";
		hyperLink.Font.Size = fontsize;
		hyperLink.Font.Bold = bold;
		return hyperLink;
	}

	private Literal CreateLiteral(string text)
	{
		Literal literal = new Literal();
		literal.Text = text;
		return literal;
	}
}
